package com.chatgpt_backend.entity.chat;

import com.alibaba.fastjson2.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


public class ServerChat<T> {
    private String model = "";
    private final ArrayList<Map<String, String>> messages = new ArrayList<>();
    private T temperature;
    private Boolean stream;
    private String user;

    public static <T> ServerChat<T> build() {
        return new ServerChat<T>();
    }

    public ServerChat<T> model(String model) {
        this.model = model;
        return this;
    }
    public ServerChat<T> role(String role) {
        if (!this.messages.isEmpty()) {
            if (messages.get(messages.size()-1).keySet().containsAll(new ArrayList<>(Arrays.asList("role", "content")))) {
                Map<String, String> map = new HashMap<>();
                map.put("role", role);
                this.messages.add(map);
            }else this.messages.get(messages.size()-1).put("role", role);
        }
        else {
            Map<String, String> map = new HashMap<>();
            map.put("role", role);
            this.messages.add(map);
        }
        return this;
    }
    public ServerChat<T> content(String content) {
        if (!this.messages.isEmpty()) {
            if (messages.get(messages.size()-1).keySet().containsAll(new ArrayList<>(Arrays.asList("role", "content")))) {
                Map<String, String> map = new HashMap<>();
                map.put("content", content);
                this.messages.add(map);
            }else this.messages.get(messages.size()-1).put("content", content);
        }
        else {
            Map<String, String> map = new HashMap<>();
            map.put("content", content);
            this.messages.add(map);
        }
        return this;
    }
    public ServerChat<T> temperature(T temperature) {
        this.temperature = temperature;
        return this;
    }

    public ServerChat<T> stream(Boolean stream) {
        this.stream = stream;
        return this;
    }
    public ServerChat<T> user(String userId) {
        this.user = userId;
        return this;
    }

    @Override
    public String toString() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("model", this.model);
        jsonObject.put("messages", this.messages);
        jsonObject.put("temperature", this.temperature);
        jsonObject.put("stream", this.stream);
        jsonObject.put("user", this.user);
        return jsonObject.toString();
    }
}
